﻿using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.PM;
using System.Collections.Generic;
using UFIDA.U9.Base.DTOs;
using UFIDA.U9.ISV.PM;
using UFIDA.U9.PPR.PurPriceList;
using UFSoft.UBF.Util.DataAccess;

namespace dz.inner.jky.api.service
{
    internal class PurPriceListService : BaseService
    {
        public U9CResult Add(DzPurPriceListDTO dto)
        {
            return util.U9Invoke(__Add, dto,dto.Org);
        }

        public void Submit(CommonDoc doc)
        {
            IDCodeNameDTO dto = new IDCodeNameDTO() { Code = doc.DocNo, ID = doc.ID };
            List<IDCodeNameDTO> dtos = new List<IDCodeNameDTO>() { dto };

            SubmitPurPriceListSRV sv = new SubmitPurPriceListSRV();

            sv.PurPriceLists = dtos;

            sv.Do();
        }

        public void Audit(CommonDoc doc)
        {
            ApprovedPurPriceListSRV sv = new ApprovedPurPriceListSRV();

            IDCodeNameDTO dto = new IDCodeNameDTO() { Code = doc.DocNo, ID = doc.ID };
            List<IDCodeNameDTO> dtos = new List<IDCodeNameDTO>() { dto };

            sv.PurPriceLists = dtos;

            sv.Do();
        }
        

        private U9CResult __Add(DzPurPriceListDTO dto)
        {            
            U9CResult result = new U9CResult();

            CreatePurPriceListSRV sv = new CreatePurPriceListSRV();

            sv.PurPriceLists = Convert(dto);

            var rtn = sv.Do();

            result.DocNo = rtn[0].Code;
            result.Id = rtn[0].ID;
            result.IsSuccess = true;

            UpdateSupplier(result);

            return result;

        }

        private void UpdateSupplier(U9CResult result)
        {
            PurPriceList entity = PurPriceList.Finder.FindByID(result.Id);

            string sql = $@"update CBO_Supplier set PriceListID = {result.Id},PriceListCode = '{result.DocNo}',PriceListName = '{result.DocNo}' where id = {entity.Supplier.ID}";
                        

            DataAccessor.RunSQL(DataAccessor.GetConn(), sql, null);
        }
        private List<PurPriceListDTO> Convert(DzPurPriceListDTO supplier)
        {
            PurPriceListDTO dto = new PurPriceListDTO();

            ObjectCopyUtil util = new ObjectCopyUtil();

            util.CopyProperty(supplier, ref dto);


            List<PurPriceListDTO> rtn = new List<PurPriceListDTO>() { dto };

            return rtn;
        }        
    }
}
